//
//  BKVersionCheckMannager.m
//  bestkeep
//
//  Created by windCould on 17/1/11.
//  Copyright © 2017年 utouu. All rights reserved.
//

#import "BKVersionCheckMannager.h"
#import "BKVersionCheckNetRequset.h"
#define ISIOS8 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 ? YES : NO)
@interface BKVersionCheckMannager ()<UIAlertViewDelegate>

@property (nonatomic,strong)UIAlertView * alertView;

@end


@implementation BKVersionCheckMannager

+(BKVersionCheckMannager *)shareInstance
{
    static BKVersionCheckMannager * instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        instance = [[BKVersionCheckMannager alloc]initConfig];
    });

    return instance;
}

-(instancetype)initConfig
{
    self = [super init];
    if (self) {
        
        
    }
    return self;
}


+(BOOL)isPushAlertViewToUpdate {
    
    NSDate *currentDate = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYYMMdd"];
    NSString *timeStrNow = [formatter stringFromDate:currentDate];
    NSString *timeStrLast = [[NSUserDefaults standardUserDefaults]objectForKey:@"lastUpdateMindPushTime"];
    if (timeStrLast == nil) {
        [BKVersionCheckMannager writeNowTime];
        return YES;
    }
    if ([timeStrLast integerValue]<[timeStrNow integerValue]) {
        [BKVersionCheckMannager writeNowTime];
        return YES;
    }
    return NO;
}

+ (void)writeNowTime {
    
    NSDate *currentDate = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYYMMdd"];
    NSString *timeStr = [formatter stringFromDate:currentDate];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        [[NSUserDefaults standardUserDefaults]setObject:timeStr forKey:@"lastUpdateMindPushTime"];
    });
}

-(void)checkBKVersion
{
    [BKVersionCheckNetRequset getVersionInfoWithResultBlock:^(id obj, NSError *error) {
        
        if (obj) {
            
            NSDictionary * dataDict = obj;
            NSArray *infoArray = [dataDict objectForKey:@"results"];
            if ([infoArray count]) {
               
                NSDictionary *releaseInfo = [infoArray objectAtIndex:0];
                NSString *lastVersion = [releaseInfo objectForKey:@"version"];
                NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
                NSString *currentVersion = [infoDic objectForKey:@"CFBundleShortVersionString"];
                lastVersion=[lastVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
                currentVersion=[currentVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
                NSLog(@"lastVersion:%@-----currentVersion:%@",lastVersion,currentVersion);
                if ([lastVersion intValue]>[currentVersion intValue]) {
                    
                    [BKVersionCheckNetRequset getIsForceUpdateBKAppVersionOrderWithResultBlock:^(id obj, NSError *error) {
                        
                        if (error) {
                            
                            return ;
                        }
                        NSDictionary * forceDict = obj;
                        
                        id data = [forceDict objectForKey:@"data"];
                        BOOL force=  [[data objectForKey:@"force"] boolValue];
                        [BKVersionCheckNetRequset getMindUserUpdateBKAppVersionWithResultBlock:^(id obj, NSError *error){
                            
                            if (obj) {
                                
                                NSDictionary * mindDict = obj;
                                int updateFlag = [[[mindDict objectForKey:@"data"] objectForKey:@"updateFlag"] intValue];
                                
                                if(updateFlag==1){
                                    
                                    if(force){
                                       
                                        if (ISIOS8) {
                                            
                                            UIAlertController * alertVC = [UIAlertController alertControllerWithTitle:@"更新" message:@"发现新版本,前往更新!" preferredStyle:UIAlertControllerStyleAlert];
                                            UIAlertAction * action = [UIAlertAction actionWithTitle:@"更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                                                
                                                NSURL *url = [NSURL URLWithString:@"https://itunes.apple.com/cn/app/id1035553463"];
                                                [[UIApplication sharedApplication]openURL:url];
                                                
                                            }];
                                            
                                            [alertVC addAction:action];
                                            UIViewController * vc = [[UIApplication sharedApplication].keyWindow rootViewController];
                                            [vc presentViewController:alertVC animated:YES completion:nil];
                                        } else {
                                        
                                        if (!_alertView) {
                                            
                                            _alertView = [[UIAlertView alloc] initWithTitle:@"更新" message:@"发现新版本,前往更新!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"更新", nil];
                                            _alertView.tag = 10001;
                                            
                                        }
                                        [_alertView show];
                                     }
                                    }else{
                        
                                        if ([BKVersionCheckMannager isPushAlertViewToUpdate]) {
                                            
                                            if (ISIOS8) {
                                                
                                                UIAlertController * alertVC = [UIAlertController alertControllerWithTitle:@"更新" message:@"发现新版本,前往更新!" preferredStyle:UIAlertControllerStyleAlert];
                                                
                                                UIAlertAction * actionCancel = [UIAlertAction actionWithTitle:@"关闭" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                                                    
                                                }];
                                                
                                                UIAlertAction * action = [UIAlertAction actionWithTitle:@"更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                                                    
                                                    NSURL *url = [NSURL URLWithString:@"https://itunes.apple.com/cn/app/id1035553463"];
                                                    [[UIApplication sharedApplication]openURL:url];
                                                    
                                                }];
                                                
                                                [alertVC addAction:action];
                                                [alertVC addAction:actionCancel];
                                                UIViewController * vc = [[UIApplication sharedApplication].keyWindow rootViewController];
                                                [vc presentViewController:alertVC animated:YES completion:nil];
                                            } else {
                                            
                                            
                                            
                                            if (!_alertView) {
                                                
                                                _alertView = [[UIAlertView alloc] initWithTitle:@"更新" message:@"发现新版本,前往更新!" delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:@"更新", nil];
                                                _alertView.tag = 10000;
                                            }
                                                
                                              [_alertView show];
                                            }
                                        }
                                    }
                                }

                                
                            }
                            
                            
                        }];
                }];
            }
          }
        }
            
    }];

}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag==10000) {
        if (buttonIndex==1) {
            
            NSURL *url = [NSURL URLWithString:@"https://itunes.apple.com/cn/app/id1035553463"];
            [[UIApplication sharedApplication]openURL:url];
        }
    }
    if (alertView.tag==10001) {
        if (buttonIndex==0) {
            
            NSURL *url = [NSURL URLWithString:@"https://itunes.apple.com/cn/app/id1035553463"];
            [[UIApplication sharedApplication]openURL:url];
        }
    }
}


@end
